package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * 拦截器类,用于提前处理用户携带的token
 *
 * @author anshuai
 * @create 2021-01-26 20:44
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.接收token值
        String token = request.getHeader("Authorization");
        if (token == null){
            //401表示无权限,如果token为空,说明没登录,所以无权限操作
            response.setStatus(401);
            return false;
        }

        //2. 从redis里找到token对应的用户
        User user = findUserByToken(token);
        if (user == null){
            response.setStatus(401);
            return false;
        }

        //3. 把User绑定到当前线程上
        /**
         * 当客户端发来的请求满足有token,并且可以从redis中拿到用户,即可放行(满足就是登陆状态)
         */
        UserHolder.setUser(user);
        return true;
    }

    /**
     * 从redis中获取用户的token信息
     *
     * @param token
     * @return
     */
    private User findUserByToken(String token) {
        //从Redis中获取当前用户信息
        String userJosn = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (userJosn == null) {
            return null;
        }

        //将取出来的字符串还原成对象
        User user = JSON.parseObject(userJosn, User.class);

        //客户端访问一次，就给redis里的用户信息续期一小时
        redisTemplate.opsForValue().set("TOKEN_" + token, userJosn, Duration.ofHours(1));

        return user;
    }
}
